import { create } from 'zustand';
import { IconMap } from '@providers/router-provider/resources';
import { selectUserRouters } from '@common/api/router_action';
import useUserStore from './user';

export interface ResourcesStore {
  resources: any[];
  loading: boolean;
  error: string | null;
  loadResources: () => Promise<void>;
  setResources: (resources: any[]) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  reset: () => void;
}

const defaultResources = [
  {
    name: "home",
    list: "/home",
    meta: {
      label: "首页",
      icon: IconMap.HomeOutlined,
    },
  }
];

const useResourcesStore = create<ResourcesStore>((set, get) => ({
  resources: defaultResources,
  loading: false,
  error: null,

  loadResources: async () => {
    const { token } = useUserStore.getState();
    if (!token) {
      set({ 
        resources: defaultResources, 
        loading: false, 
        error: null 
      });
      return;
    }
    set({ loading: true, error: null });
    try {
      const res = await selectUserRouters() as any;
      if (res.data) {
        const menus = res.data.map((item: any) => {
          const icon = IconMap[item.meta.icon as keyof typeof IconMap];
          return {
            ...item,
            meta: {
              ...item.meta,
              icon: icon || undefined,
            }
          };
        });

        const finalResources = [...defaultResources, ...menus];
        set({ 
          resources: finalResources, 
          loading: false, 
          error: null 
        });
        
        // 同时更新user store中的resources
        useUserStore.getState().updateResources(finalResources);
      } else {
        set({ 
          resources: defaultResources, 
          loading: false, 
          error: null 
        });
      }
    } catch (error) {
      console.error('获取菜单资源失败:', error);
      set({ 
        resources: defaultResources, 
        loading: false, 
        error: '获取菜单失败' 
      });
    }
  },

  setResources: (resources: any[]) => {
    set({ resources });
  },

  setLoading: (loading: boolean) => {
    set({ loading });
  },

  setError: (error: string | null) => {
    set({ error });
  },

  reset: () => {
    set({ 
      resources: defaultResources, 
      loading: false, 
      error: null 
    });
  },
}));

export default useResourcesStore; 